package com.iot.framework.rabbitmq.service;


import com.alibaba.fastjson2.JSONObject;
import com.iot.common.enums.DeviceAlarmType;
import com.iot.common.enums.DeviceConnectType;
import com.iot.common.enums.DeviceStatusRecordType;
import com.iot.common.enums.DeviceStatusType;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.RedisUtil;
import com.iot.system.domain.DeviceDetails;
import com.iot.system.domain.DeviceState;
import com.iot.system.domain.DeviceStateLogs;
import com.iot.system.service.IDeviceDetailsService;
import com.iot.system.service.IDeviceStateLogsService;
import com.iot.system.service.IDeviceStateService;
import com.iot.system.vo.DeviceAlarmVo;
import com.iot.system.vo.DeviceStateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DeviceAlarmService {

    @Resource
    private IDeviceDetailsService iDeviceDetailsService;

    @Resource
    private IDeviceStateService iDeviceStateService;

    @Resource
    private IDeviceStateLogsService iDeviceStateLogsService;



    //判断消息类型 当前消息属于设备状态  分为设备上线 设备下线
    public void deviceAlarm(String message) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            log.info("DeviceAlarmService_deviceAlarm_设备报警状态转换完成:{}",jsonObject);
            DeviceAlarmVo deviceAlarmVo = jsonObject.toJavaObject(DeviceAlarmVo.class);
            //避免短期重复消费  15秒的锁
            boolean b = RedisUtil.KeyOps.hasKey("alarm:"+deviceAlarmVo.getCredentials() + ":" + deviceAlarmVo.getAlarm());
            if (b) {
                return;
            }
            //获取设备详情
            DeviceDetails deviceDetails = iDeviceDetailsService.selectDeviceDetailsByToken(deviceAlarmVo.getCredentials());
            if(Objects.isNull(deviceDetails)){
                return;
            }
            processingDeviceState(deviceAlarmVo, deviceDetails);
            //设备状态更新记录
            processingDeviceStateLogs(deviceAlarmVo, deviceDetails);
            RedisUtil.StringOps.setEx("alarm:"+deviceAlarmVo.getCredentials()+":"+deviceAlarmVo.getAlarm(),"1",15L, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("DeviceAlarmService_deviceAlarm_设备报警状态转换异常:{}",e);
        }

    }

    private void processingDeviceStateLogs(DeviceAlarmVo deviceStateVo, DeviceDetails deviceDetails) {
        if (Objects.equals(deviceStateVo.getAlarm(), DeviceAlarmType.ALARM_OCCURRED.getNumber())) {
            DeviceStateLogs deviceStateLogs = new DeviceStateLogs();
            deviceStateLogs.setDeviceId(deviceDetails.getId());
            deviceStateLogs.setDeviceBootUp(new Date());
            deviceStateLogs.setDeviceState(DeviceStatusRecordType.ALARM.getNumber());
            deviceStateLogs.setCreateTime(new Date());
            deviceStateLogs.setUpdateTime(new Date());
            deviceStateLogs.setCreateBy("10101010");
            deviceStateLogs.setUpdateBy("10101010");
            deviceStateLogs.setIsDeleted(0);
            iDeviceStateLogsService.insertDeviceStateLogs(deviceStateLogs);
        }

        if (Objects.equals(deviceStateVo.getAlarm(), DeviceAlarmType.ALARM_CLEAR.getNumber())) {
            //如果是报警解除 则查询最近一次的报警
            DeviceStateLogs deviceStateLogs = iDeviceStateLogsService.selectDeviceStateLogsByDeviceId(deviceDetails.getId(),DeviceStatusRecordType.ALARM.getNumber());
            if (Objects.isNull(deviceStateLogs.getId())) {
                return;
            }
            deviceStateLogs.setDeviceShutDown(new Date());
            iDeviceStateLogsService.updateDeviceStateLogs(deviceStateLogs);
        }
    }

    //设备状态处理
    private void processingDeviceState(DeviceAlarmVo deviceAlarmVo, DeviceDetails deviceDetails) {
        log.info("DeviceAlarmService_processingDeviceState_设备报警状态处理开始:{}",deviceAlarmVo);
        DeviceState deviceState = iDeviceStateService.getDeviceStateByDeviceId(deviceDetails.getId());
        if (Objects.isNull(deviceState.getId())) {
            log.info("DeviceAlarmService_processingDeviceState_当前设备不存在状态，所以无法将开机状态改为报警状态");
            return;
        }
        log.info("DeviceAlarmService_processingDeviceState_设备状态不为空处理开始:{}",deviceAlarmVo);
        if (Objects.nonNull(deviceState.getId())) {
            boolean isBootUp =Objects.equals(deviceState.getStateType(), DeviceStatusType.BOOT_UP.getNumber())||Objects.equals(deviceState.getStateType(), DeviceStatusType.DEVICE_RUN.getNumber());
            //如果当前设备处于开机状态 发生了报警
            boolean equals = Objects.equals(deviceAlarmVo.getAlarm(), DeviceAlarmType.ALARM_OCCURRED.getNumber());

            if (isBootUp&&equals) {
                //如果当前设备处于链接中的状态 发生了报警
                deviceState.setStateType(DeviceStatusType.FAILURE.getNumber());
                deviceState.setStateTime(new Date());
                iDeviceStateService.updateDeviceState(deviceState);
            }
            //如果当前设备处于报警状态 发生了报警解除
            if (Objects.equals(deviceAlarmVo.getAlarm(), DeviceAlarmType.ALARM_CLEAR.getNumber())&&Objects.equals(deviceState.getStateType(), DeviceStatusType.FAILURE.getNumber())){
                deviceState.setStateType(DeviceStatusType.STOP_FAILURE.getNumber());
                deviceState.setStateTime(new Date());
                iDeviceStateService.updateDeviceState(deviceState);
            }
            log.info("DeviceAlarmService_processingDeviceState_设备状态不为空处理结束:{}",deviceState);
            return;
        }
    }
}
